package com.example.drools.config;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@Configuration
public class KieConfig {

    // 定义所有业务规则文件路径
    private static final List<String> RULE_FILES = Arrays.asList(
        "rules/personalization.drl",  // 个性化推荐规则
        "rules/risk-control.drl",     // 风控规则
        "rules/pricing.drl"           // 定价规则
    );

    @Bean
    public KieContainer kieContainer() throws IOException {
        KieServices kieServices = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        
        // 批量加载所有规则文件
        for (String ruleFile : RULE_FILES) {
            try {
                ClassPathResource resource = new ClassPathResource(ruleFile);
                String ruleContent = new String(resource.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
                
                // 将规则内容写入 KieFileSystem
                kieFileSystem.write("src/main/resources/" + ruleFile, ruleContent);
                System.out.println("已加载规则文件: " + ruleFile);
            } catch (IOException e) {
                System.out.println("规则文件不存在，跳过: " + ruleFile + " - " + e.getMessage());
                // 继续加载其他文件，不中断整个流程
            }
        }
        
        KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
        kieBuilder.buildAll();
        
        KieModule kieModule = kieBuilder.getKieModule();
        
        if (kieBuilder.getResults().hasMessages(org.kie.api.builder.Message.Level.ERROR)) {
            throw new RuntimeException("规则编译错误:\n" + kieBuilder.getResults().toString());
        }
        
        System.out.println("所有规则文件加载完成，KieContainer 初始化成功");
        return kieServices.newKieContainer(kieModule.getReleaseId());
    }
}